const BaseController = require("./base/base");
const Result = require("../utils/result");
const jwt = require("jsonwebtoken");
const usersService = require("../service/users")
class IndexController extends BaseController {
    constructor() {
        super();
        this.key = "guoyei";
        this.hostname = "http://127.0.0.1:3000"
    }
    async index(req, res, next) {
        try {
            const face = [
                { url: this.hostname + "/reg", method: "post", params: { username: "String", password: "String" } },
                { url: this.hostname + "/login", method: "post", params: { username: "String", password: "String" } },
                { url: this.hostname + "/verify", method: "get", params: { username: "String" }, headers: { authorization: "String" } },
                { url: this.hostname + "/check", method: "get", params: { username: "String" } }
            ]
            res.json(Result.ok("success", face));
        } catch (err) {
            res.json(Result.error(err));
        }
    }
    async login(req, res, next) {
        try {
            const { username, password } = req.body;
            if (!username || !password) return res.json(Result.fail("用户名或密码错误"));
            let userinfo = await usersService.login({ username, password });
            if (!userinfo || userinfo.length == 0) return res.json(Result.fail("用户名或密码错误"));
            const authorization = jwt.sign({ _id: userinfo[0]._id, username: userinfo[0].username }, this.key, { expiresIn: "1d" });
            //{"admin":"test","iat":1635397028,"exp":1635483428}
            res.json(Result.ok("success", { _id: userinfo[0]._id, username, authorization }));
        } catch (err) {
            res.json(Result.error(err));
        }
    }
    async verify(req, res, next) {
        try {
            const { username } = req.query;
            if (!username) return res.json(Result.fail("username错误"));
            const { authorization } = req.headers; //headers 里面的所有key都会是小写
            if (!authorization) return res.json(Result.fail("authorization错误"));
            const data = jwt.verify(authorization, this.key); //{"username":"admin","iat":1635349069,"exp":1635435469}
            if (username != data.username) return res.json(Result.fail("username不匹配"));
            res.json(Result.ok("success", data));
        } catch (err) {
            //篡改{"name":"JsonWebTokenError","message":"invalid token"}
            //过期{"name":"TokenExpiredError","message":"jwt expired","expiredAt":"2021-10-28T03:28:45.000Z"}
            res.json(Result.error(err));
        }
    }
    async reg(req, res, next) {
        try {
            const { username, password } = req.body;
            if (!username || !password) return res.json(Result.fail("用户名或密码不能为空"));

            let ret = await usersService.findByUsername(username);
            if (ret && ret.length > 0) return res.json(Result.fail("用户名已存在"));

            ret = await usersService.reg({ username, password });
            //增加或修改或删除,mysql和mongodb返回的数据是不一样的
            //{ acknowledged: true, insertedId: ObjectId("616aa947d1a35b74c230b5af") }
            //{"fieldCount":0,"affectedRows":1,"insertId":14,"serverStatus":2,"warningCount":0,"message":"","protocol41":true,"changedRows":0}
            !ret.insertedId && !ret.insertId ?
                res.json(Result.fail("注册失败", ret)) :
                res.json(Result.ok("注册成功", ret));
        } catch (err) {
            res.json(Result.error(err));
        }
    }
    async check(req, res, next) {
        try {
            const { username } = req.query;
            if (!username) return res.json(Result.fail("username错误"));
            let ret = await usersService.findByUsername(username);
            ret && ret.length > 0 ?
                res.json(Result.fail("用户名已存在")) :
                res.json(Result.ok("success"));
        } catch (err) {
            res.json(Result.error(err));
        }
    }
}
module.exports = new IndexController().resolve();